package com.zide.file.service.impl;

import com.zide.common.constant.HttpStatus;
import com.zide.common.exception.ServiceException;
import com.zide.file.utils.FileUploadUtils;
import com.zide.file.utils.FileUtils;
import com.zide.file.config.LocalFileConfig;
import com.zide.file.domain.vo.result.FileUploadResultVO;
import com.zide.file.service.LocalFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 本地文件管理服务实现
 * @author 石添添
 * @date 2024-09-12 15:20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LocalFileServiceImpl implements LocalFileService {
    private final FileUploadUtils fileUploadUtils;
    @Override
    public FileUploadResultVO singleUpload(MultipartFile file, String fileModule) {
        try {
            // 上传并返回新文件名称
            String url = fileUploadUtils.upload(fileModule, file);
            FileUploadResultVO fileResultVO = new FileUploadResultVO();
            fileResultVO.setUrl(url);
            fileResultVO.setFilename(FileUtils.getName(url));
            return fileResultVO;
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.ERROR,e.getMessage());
        }
    }

    @Override
    public List<FileUploadResultVO> multipleUpload(List<MultipartFile> files, String fileModule) {
        try {
            List<FileUploadResultVO> list = new ArrayList<>();

            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String url = fileUploadUtils.upload(fileModule, file);
                FileUploadResultVO fileResultVO = new FileUploadResultVO();
                fileResultVO.setUrl(url);
                fileResultVO.setFilename(FileUtils.getName(url));
                list.add(fileResultVO);
            }
            return list;
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.ERROR,e.getMessage());
        }
    }
}
